package com.fivefu.core.camera.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivefu.base.common.utils.date.DateUtils;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.camera.constant.StatusEnum;
import com.fivefu.core.camera.entity.*;
import com.fivefu.core.camera.mapper.DbMonitorWorkorderMapper;
import com.fivefu.core.camera.services.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.core.camera.vo.response.MonitorWorkerBean;
import com.fivefu.core.skyeye.event.services.DbAiSceneTypeService;
import com.fivefu.module.event.entity.response.DbAiEventTypeRes;
import com.fivefu.module.event.services.DbAiEventTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 工单表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-09-21 20:12:53
 */
@Service
public class DbMonitorWorkorderServiceImpl extends ServiceImpl<DbMonitorWorkorderMapper, DbMonitorWorkorder> implements DbMonitorWorkorderService {

    @Autowired
    private DbMonitorStatusService dbMonitorStatusService;

    @Autowired
    private DbAiSceneTypeService dbAiSceneTypeService;

    @Autowired
    private DbMonitorEventExamineService dbMonitorEventExamineService;

    @Autowired
    private DbMonitorWorkorderRecordService dbMonitorWorkorderRecordService;

    @Autowired
    private DbMonitorCameraService dbMonitorCameraService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private DbAiEventTypeService dbAiEventTypeService;

    @Autowired
    private DbMonitorWorkorderImageService dbMonitorWorkorderImageService;

    /**
     * 生成工单编号
     * @return
     */
    public Long createWorkorderCode(){
        String beginStr = LocalDate.now().toString().replaceAll("-","");

        //查询最大的工单编号
        QueryWrapper<DbMonitorWorkorder> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.apply("order_id like '" + beginStr + "%'");
        wrapper.orderByDesc("id");
        wrapper.select("order_id");
        wrapper.last("limit 1");
        DbMonitorWorkorder order = baseMapper.selectOne(wrapper);

        Long id = Long.parseLong(beginStr+"00000");
        if (order != null){
            id = Long.parseLong(order.getOrderId());
        }
        id ++;
        return id;
    }

    /**
     * 编辑工单信息
     * @param workorder 工单信息
     * @param userid 操作用户
     * @return
     */
    @Override
    public Long editMonitorWorkorder(DbMonitorWorkorder workorder, String userid){
        LocalDateTime time = LocalDateTime.now();
        workorder.setUpdatedBy(userid);
        workorder.setUpdatedTime(time);
        if (workorder.getId() != null){
            baseMapper.updateById(workorder);
        }else{
            Long orderId = createWorkorderCode();
            workorder.setOrderId(orderId + "");

            workorder.setCreatedBy(userid);
            workorder.setCreatedTime(time);
            workorder.setIsDelete(0);
            baseMapper.insert(workorder);
        }
        return workorder.getId();
    }

    /**
     * 编辑工单信息
     * @param workorder 工单信息
     * @param images 图片信息
     * @param userid 操作用户编号
     * @return
     */
    @Override
    public Long editMonitorWorkorder(DbMonitorWorkorder workorder, List<DbMonitorWorkorderImage> images, String userid){
        Long orderId = editMonitorWorkorder(workorder, userid);
        //编辑工单图片信息
        dbMonitorWorkorderImageService.editWorkorderImage(orderId, images, userid);
        /*//编辑处置记录
        DbMonitorWorkorderRecord record = new DbMonitorWorkorderRecord();
        record.setLink(workorder.getOrderStatus());
        record.setDealUser(workorder.getOrderCreateUser());
        record.setDealDesc(workorder.getOrderCreateUser() + "生成了工单编号为【" + orderId + "】的工单");
        dbMonitorWorkorderRecordService.createWorkorderRecord(orderId, record, userid);*/
        return orderId;
    }

    /**
     *工单列表
     * @param page 页码
     * @param limit 数量
     * @param type 工单类型
     * @param orderBigType 问题大类
     * @param orderSmallType 问题小类
     * @param orderAreaid 所属城区
     * @param orderPushStatus 状态
     * @param cameraName 探头名称
     * @param cStime 生成时间的开始
     * @param cEtime 生成时间的结束
     */
    @Override
    public Page<MonitorWorkerBean> queryMonitorWorkerList(Integer page, Integer limit,String type,String orderBigType, String orderSmallType, String orderAreaid, String orderPushStatus, String cameraName, String cStime,String cEtime) {
        IPage<MonitorWorkerBean> iPage = new Page<>(page, limit);

        //分页查询
        Page<MonitorWorkerBean> beanPage = baseMapper.queryMonitorWorkerList(iPage,type,orderBigType, orderSmallType, orderAreaid, orderPushStatus, cameraName,cStime, cEtime);
        beanPage.getRecords().forEach(workerBean->{
            //所属城区
            if (StrUtils.isNotEmpty(workerBean.getOrderAreaid())){
                String areaName = regionService.queryAreaNameByCode(workerBean.getOrderAreaid());
                workerBean.setOrderAreaName(areaName);
            }
            //设置工单类型
            Integer type1 = workerBean.getType();
            if (type1 == 1){
                workerBean.setTypeName("智能工单");
            }else if (type1 == 2){
                workerBean.setTypeName("人工工单");
            }

            //推送状态
            String status = workerBean.getOrderPushStatus();
            if (StrUtils.isNotEmpty(status)){
                String s = dbMonitorStatusService.queryStatusNameById(Long.parseLong(status));
                workerBean.setOrderPushStatus(s);
            }
            //问题类型
            String orderType = workerBean.getOrderType();
            if (StrUtils.isNotEmpty(orderType)){
                DbAiEventTypeRes dbAiEventTypeRes = dbAiEventTypeService.queryEventTypeDetailByCode(orderType, null);
                if (dbAiEventTypeRes != null){
                    workerBean.setOrderType(dbAiEventTypeRes.getEventTypeName());
                }
            }
            //问题大类
            String bigType = workerBean.getOrderBigType();
            if (StrUtils.isNotEmpty(orderType)){
                DbAiEventTypeRes dbAiEventTypeRes = dbAiEventTypeService.queryEventTypeDetailByCode(bigType, null);
                if (dbAiEventTypeRes != null){
                    workerBean.setOrderBigType(dbAiEventTypeRes.getEventTypeName());
                }
            }
            //问题小类
            String smallType = workerBean.getOrderSmallType();
            if (StrUtils.isNotEmpty(orderType)){
                DbAiEventTypeRes dbAiEventTypeRes = dbAiEventTypeService.queryEventTypeDetailByCode(smallType, null);
                if (dbAiEventTypeRes != null){
                    workerBean.setOrderSmallType(dbAiEventTypeRes.getEventTypeName());
                }
            }
        });
        return beanPage;
    }

    /**
     *
     * 格式化工单信息
     * @param monitorWorkorder
     */
    @Override
    public Map<String, Object> formatMonitorWorker(DbMonitorWorkorder monitorWorkorder) {
        Map<String, Object> map = new HashMap<>();
        map.put("id",monitorWorkorder.getId());
        map.put("orderId",monitorWorkorder.getOrderId()); //工单编号
        map.put("eventId",monitorWorkorder.getEventId()); //事件编号
        map.put("eventOrderId",monitorWorkorder.getEventOrderId()); //上报后反馈案卷编号

        //问题类型
        String orderType = monitorWorkorder.getOrderType();
        if (StrUtils.isNotEmpty(orderType)){
            DbAiEventTypeRes dbAiEventTypeRes = dbAiEventTypeService.queryEventTypeDetailByCode(orderType, null);
            if (dbAiEventTypeRes != null){
                map.put("orderType",dbAiEventTypeRes.getEventTypeName()); //问题类型
            }
        }
        //问题大类
        String bigType = monitorWorkorder.getOrderBigType();
        if (StrUtils.isNotEmpty(orderType)){
            DbAiEventTypeRes dbAiEventTypeRes = dbAiEventTypeService.queryEventTypeDetailByCode(bigType, null);
            if (dbAiEventTypeRes != null){
                map.put("orderBigType",dbAiEventTypeRes.getEventTypeName()); //问题大类
            }
        }
        //问题小类
        String smallType = monitorWorkorder.getOrderSmallType();
        if (StrUtils.isNotEmpty(orderType)){
            DbAiEventTypeRes dbAiEventTypeRes = dbAiEventTypeService.queryEventTypeDetailByCode(smallType, null);
            if (dbAiEventTypeRes != null){
                map.put("orderSmallType",dbAiEventTypeRes.getEventTypeName()); //问题小类
            }
        }

        if (StrUtils.isNotEmpty(monitorWorkorder.getOrderAreaid())){
            String s = regionService.queryAreaNameByCode(monitorWorkorder.getOrderAreaid());
            map.put("orderAreaName",s); //所属城区
        }
        if (StrUtils.isNotEmpty(monitorWorkorder.getOrderAreaid()) && StrUtils.isNotEmpty(monitorWorkorder.getOrderStreetid())){
            String s = regionService.queryStreetNameByCode(monitorWorkorder.getOrderAreaid(), monitorWorkorder.getOrderStreetid());
            map.put("orderStreetName",s); //所属街道
        }
        map.put("cameraName",monitorWorkorder.getCameraName()); //探头名称
        map.put("cameraCode",monitorWorkorder.getCameraCode()); //探头编号

        if (monitorWorkorder.getOrderCreateTime() != null){
            map.put("orderCreateTime",DateUtils.formatNormal(monitorWorkorder.getOrderCreateTime())); //生成时间
        }else {
            map.put("orderCreateTime",""); //生成时间
        }

        if (StrUtils.isNotEmpty(monitorWorkorder.getCameraCode())){
            DbMonitorCamera dbMonitorCamera = dbMonitorCameraService.queryMonitorCameraByCode(monitorWorkorder.getCameraCode());
            if (dbMonitorCamera != null){
                map.put("cameraStatus",dbMonitorCamera.getCameraStatus()); //探头状态
            }
        }
        map.put("orderDescription",monitorWorkorder.getOrderDescription()); //问题描述
        map.put("orderAddress",monitorWorkorder.getOrderAddress()); //详细地址
        map.put("orderLongitude",monitorWorkorder.getOrderLongitude()); //经度
        map.put("orderLatitude",monitorWorkorder.getOrderLatitude()); //纬度
        return map;
    }

    /**
     * 通过主键编号查询工单详情
     * @param orderId 工单编号
     * @return
     */
    @Override
    public DbMonitorWorkorder queryWorkorderById(Long orderId){
        DbMonitorWorkorder dbMonitorWorkorder = baseMapper.selectById(orderId);
        return dbMonitorWorkorder;
    }

    /**
     *
     * 工单详情
     * @param orderId 工单id
     */
    @Override
    public Map<String, Object> queryMonitorWorkDetail(Long orderId) {
        HashMap<String, Object> detail = new HashMap<>();
        DbMonitorWorkorder dbMonitorWorkorder = queryWorkorderById(orderId);
        if (dbMonitorWorkorder != null){
            //工单基础信息
            Map<String, Object> workorMap = formatMonitorWorker(dbMonitorWorkorder);
            detail.put("workorder",workorMap);

            //处置记录
            List<Map<String,Object>> recordMapList = new ArrayList<>();
            List<DbMonitorWorkorderRecord> recordList = dbMonitorWorkorderRecordService.queryWorkorderRecordListByOrderId(orderId);
            recordList.forEach(record -> {
                Map<String, Object> recordMap = dbMonitorWorkorderRecordService.formatMonitorWorkorderRecord(record);
                recordMapList.add(recordMap);
            });
            detail.put("recordList",recordMapList);

            //工单依据
            List<DbMonitorWorkorderImage> list = dbMonitorWorkorderImageService.queryWorkorderImageListByOrderId(orderId);
            List<Map<String, Object>> mapList = new ArrayList<>();
            if (list != null && list.size() > 0){
                list.forEach(l->{
                    Map<String, Object> image = dbMonitorWorkorderImageService.formatWorkorderImage(l);
                    mapList.add(image);
                });
            }
            detail.put("imageList",mapList);

            //审核意见
            if (dbMonitorWorkorder.getEventId() != null) {
                DbMonitorEventExamine examine = dbMonitorEventExamineService.queryExamineByEventId(dbMonitorWorkorder.getEventId());
                if (examine != null) {
                    Map<String, Object> eventExamine = dbMonitorEventExamineService.formatEventExamine(examine);
                    detail.put("examine", eventExamine);
                }
            }
            //时间
        }
        return detail;
    }

    /**
     * 查询案卷列表
     * @param orderStatus 案卷状态
     * @param orderPushStatus 推送状态
     * @return
     */
    @Override
    public List<DbMonitorWorkorder> queryEventListByStatus(Long orderStatus, Long orderPushStatus){
        QueryWrapper<DbMonitorWorkorder> wrapper = new QueryWrapper<>();
        if (orderStatus != null){//案卷状态
            wrapper.eq("order_status",orderStatus);
        }
        if (orderPushStatus != null){//推送状态
            wrapper.eq("order_push_status",orderPushStatus);
        }
        List<DbMonitorWorkorder> list = baseMapper.selectList(wrapper);
        return list;
    }

    /**
     * 查询已经生成工单的数据信息
     * @return
     */
    @Override
    public List<DbMonitorWorkorder> queryWorkorderList() {
        QueryWrapper<DbMonitorWorkorder> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 根据事件id集查询工单
     * @param eventIds  事件id集
     * @return
     */
    @Override
    public List<DbMonitorWorkorder> queryWorkOrderListByEventIds(List<Long> eventIds) {
        QueryWrapper<DbMonitorWorkorder> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.in("event_id",eventIds);
        return baseMapper.selectList(wrapper);
    }
}
